package com.lsh.oms.core.service.bills;

import com.lsh.oms.core.constant.BillsConstant;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.bills.MessageBean;
import com.lsh.oms.core.service.bills.impl.AbstractKafkaMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author peter
 * @date 18/5/17
 */
@Service
@Slf4j
public class HandlerKafkaMessage implements InitializingBean {

    private final Map<String, String> tableServiceMap = new HashMap<>();

    @Autowired
    private Map<String, AbstractKafkaMessageService> kafkaMessageBillServices;

    public void handlerKafkaMessage(MessageBean billMessage) {
        try {
            String beanNameKey = tableServiceMap.get(billMessage.getOperateBill());
            if (StringUtils.isBlank(beanNameKey)) {
                log.info("beanNameKey is null ,operateBill is {}", billMessage.getOperateBill());
                return;
            }

            AbstractKafkaMessageService kafkaMessageService = kafkaMessageBillServices.get(beanNameKey);
            if (kafkaMessageService == null) {
                log.info("kafkaMessageService is null ,operateBill is {}", billMessage.getOperateBill());
                return;
            }

            kafkaMessageService.handleKafkaMessage(billMessage);
            log.info("HandlerKafkaMessage : end");
        } catch (BusinessException e) {
            log.error("HandlerKafkaMessage ::: BusinessException:", e);
            throw new BusinessException(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("HandlerKafkaMessage ::: Exception:", e);
            throw new BusinessException(ReturnCode.UPDATE_FAIL, e.getMessage());
        }

    }

    @Override
    public void afterPropertiesSet() throws BusinessException {
        tableServiceMap.put(BillsConstant.BillTYPE_DELIVERY_BILL, "orderShippingTmsService");
        tableServiceMap.put(BillsConstant.BillTYPE_RETURN_BILL, "orderReturnTmsService");
        tableServiceMap.put(BillsConstant.BillTYPE_SIGN_BILL, "orderReceiptTmsService");
    }
}
